package db

import (
	"database/sql"
	"github.com/google/uuid"
	"gomonitor-server/src/dto"
	"gomonitor-server/src/mylog"
	"net"
)

func hostOnlineLog(connectionInfo *dto.ConnectionInfo) {
	dbTool, err := GetConnection()
	if err != nil {
		// 处理错误
		mylog.Logger.Error("hostOnlineLog连接MySQL失败", err)
		return
	}
	sysInfo := connectionInfo.LastSysInfo
	if sysInfo != nil {
		var ip string
		if len(sysInfo.NetInfo) > 0 {
			ip = sysInfo.NetInfo[0].Ip
		} else {
			return
		}
		host, port, err := net.SplitHostPort(connectionInfo.Conn.RemoteAddr().String())
		if err != nil {
			mylog.Logger.Error("hostOnlineLogerror reading from tcp: ", err)
			return
		}
		_, err = dbTool.Exec("insert into t_host_state_log (id, hostname, ip, remote_ip, remote_port, start_time, end_time) "+
			" values (?,?,?,?,?,?,?)", uuid.New().String(), sysInfo.Hostname, ip, host, port, connectionInfo.StartTime, nil)
		if err != nil {
			// 处理错误
			mylog.Logger.Error("hostOnlineLog更新主机状态失败", err)
			return
		}
	}
}
func hostOfflineLog(connectionInfo *dto.ConnectionInfo) {
	dbTool, err := GetConnection()
	if err != nil {
		// 处理错误
		mylog.Logger.Error("hostOnlineLog连接MySQL失败", err)
		return
	}
	sysInfo := connectionInfo.LastSysInfo
	if sysInfo != nil {
		var ip string
		if len(sysInfo.NetInfo) > 0 {
			ip = sysInfo.NetInfo[0].Ip
		} else {
			return
		}

		rows, err := dbTool.Query("SELECT id FROM t_host_state_log"+
			"  WHERE hostname=? AND ip=?  AND end_time IS NULL  "+
			"  ORDER BY start_time DESC  LIMIT 1", sysInfo.Hostname, ip)
		defer func(rows *sql.Rows) {
			err := rows.Close()
			if err != nil {
				mylog.Logger.Error("hostOnlineLog查询主机状态日志失败", err)
			}
		}(rows)
		if err != nil {
			mylog.Logger.Error("hostOnlineLog查询主机状态日志失败", err)
			return
		}
		for rows.Next() {
			var id string
			err := rows.Scan(&id)
			if err != nil {
				// 处理错误
				mylog.Logger.Error("hostOnlineLog查询主机状态失败", err)
				return
			} else {
				_, err = dbTool.Exec("update t_host_state_log set end_time=? where id=?", connectionInfo.EndTime, id)
				if err != nil {
					// 处理错误
					mylog.Logger.Error("hostOnlineLog更新主机状态失败", err)
					return
				}
			}
		}
	}
}
